package com.allsofts.pattern.course.observer.core;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @ProjectName: pattern
 * @Package: com.allsofts.pattern.course.observer.core
 * @description:
 * @Author: liyc
 * @CreateDate: 2018/8/22 下午10:55
 * @Version: 1.0
 * <p>Copyright: Copyright (c) 2018</p>
 */
public class EventListener {

    protected Map<Enum,Event> events = new HashMap<>();
    public void addListener(Enum eventType, Object target, Method callback){
        //注册事件
        //用反射调用这个方法
        events.put(eventType,new Event(target,callback));

    }

    private void trigger(Event e){
        e.setSource(this);
        e.setTime(System.currentTimeMillis());
        try {
            e.getCallback().invoke(e.getTarget(),e);
        } catch (Exception ex) {
            ex.printStackTrace();
        }


    }

    protected void trigger(Enum call){
        if (!this.events.containsKey(call)){
            return;
        }

        trigger(this.events.get(call).setTrigger(call.toString()));

    }
}
